package ktor

import com.liftric.kvault.KVault
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.bearerAuth
import io.ktor.client.request.get
import io.ktor.client.request.parameter
import io.ktor.client.request.patch
import io.ktor.http.path
import ktor.models.ApiResponse
import models.User
import sendRequest

class KtorUserDataSource(
    private val httpClient: HttpClient,
    private val kVault: KVault
) {
    private val token: String
        get() = kVault.string("token") ?: ""

    // user

    suspend fun me(): Result<User?> {
        return sendRequest {
            httpClient.get {
                url {
                    path("/inventory/api/users/me")
                }
                bearerAuth(token)
            }.body<ApiResponse<User>>().data
        }
    }

    fun logout() {
        kVault.clear()
    }

    // admin

    suspend fun users(): Result<List<User>?> {
        return sendRequest {
            httpClient.get {
                url {
                    path("/inventory/api/users")
                }
                bearerAuth(token)
            }.body<ApiResponse<List<User>>>().data
        }
    }

    suspend fun user(id: Int): Result<User?> {
        return sendRequest {
            httpClient.get {
                url {
                    path("/inventory/api/users/$id")
                }
                bearerAuth(token)
            }.body<ApiResponse<User>>().data
        }
    }

    suspend fun delete(id: Int): Result<Int?> {
        return sendRequest {
            httpClient.get {
                url {
                    path("/inventory/api/users/$id")
                }
                bearerAuth(token)
            }.body<ApiResponse<Int>>().data
        }
    }

    suspend fun updateUser(
        id: Int,
        role: String? = null,
        locationId: Int? = null
    ): Result<Int?> {
        return sendRequest {
            httpClient.patch {
                url {
                    path("/inventory/api/users/$id")
                    parameter("role", role)
                    parameter("locationId", locationId)
                }
                bearerAuth(token)
            }.body<ApiResponse<Int>>().data
        }
    }
}